﻿using System;
using System.Collections.Generic;
using System.Web.Security;
using Newtonsoft.Json;
using Sharp.WeShare.Applet.Login.Entity;
using Sharp.WeShare.Common;

namespace Sharp.WeShare.Applet.Login
{
    public class LoginApi
    {
        /// <summary>
        /// code换取session_key
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static CodeToSessionRes CodeToSession(string appId, string secret, string code)
        {
            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";
            return Utils.GetResult<CodeToSessionRes>(url);
        }
        /// <summary>
        /// code换取第三方session
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static MySession CodeToMySession(string appId, string secret, string code)
        {
            var res = CodeToSession(appId, secret, code);
            if (res.errcode == 0)
            {
                var guid = Utils.GetGuid();
                var mykey = Utils.GetCoding($"{appId}{code}{secret}{guid}");
                return new MySession { errcode = 0,Key = res.session_key,MyKey = mykey,ExpiresIn = res.expires_in,OpenId = res.openid};
            }
            return new MySession {errmsg = res.errmsg,errcode = res.errcode};
        }
        /// <summary>
        /// 根据密文，进行解密，获取用户信息
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="sessionKey"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static UserInfo GetUserInfo(string encryptedData, string sessionKey, string iv)
        {
            return JsonConvert.DeserializeObject<UserInfo>(Utils.Decrypt(encryptedData, sessionKey, iv));
        }
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="sessionKey"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        public static bool ValidSign(string rawData, string sessionKey, string signature)
        {
            var hashPasswordForStoringInConfigFile = FormsAuthentication.HashPasswordForStoringInConfigFile(rawData + sessionKey, "SHA1");
            if (hashPasswordForStoringInConfigFile != null)
            {
                var tempsign = hashPasswordForStoringInConfigFile.ToLower();
                return signature == tempsign;
            }
            return false;
        }
    }
}
